import { useEffect, useState } from 'react'
import ReportContent from './components/ReportContent'
import HCTitle from '@/components/hc-title'
import dayjs from 'dayjs'
import api from '@/api'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { copyText } from '@/utils/copy';
import { message } from 'antd';
import { useDispatch, useSelector } from "react-redux";
import { closeCurrentTab } from '@/store/modules/tabListSlice';

const Report = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const tabList = useSelector(state => state.tabList.tabList)
  const [form, setForm] = useState({})
  const [formOptions, setFormOptions] = useState({})
  
  // 读取参数
  const [searchParams] = useSearchParams()
  const projectId = searchParams.get('projectId') || 15
  const type = searchParams.get('type') || 'daily' // daily || month
  const reportTime = dayjs() // 默认当天
  
  const [initialValues, setInitialValues] = useState({
    project_id: +projectId,
    reportTime,
  })
  const title = '日报'
  const btnGroup = [
    { text: '打卡', type: 'primary', danger: true, action: 'handleSubmit' },
    { text: '复制', type: 'primary', action: 'handleCopy' },
  ]

  const initProjectList = () => {
    api.dataset.getChildrenById({ id: 14 }).then((res) => {
      const projectList = res.data.map(item => ({ id: item.id, value: item.name }))
      setFormOptions(formOptions => ({
        ...formOptions,
        projectList
      }))
    })
  }

  const getNewReport = () => {
    switch (type) {
      case 'daily': {
        const startOn = dayjs().add(-1, 'day')
        const finishOn = dayjs()
        const params = {
          project_id: projectId,
          start_on: startOn,
          finish_on: finishOn
        }
        api.board.getReport(params).then(({ data }) => {
          const result = [`${finishOn.format('YYYY-MM-DD')} 日报`]
          data.forEach((item, index) => {
            result.push(`${index + 1}.【${item.type_name}】${item.content} 100%`)
          })
          setInitialValues({
            ...initialValues,
            content: result.join('\n')
          })
        })
        break
      }
      case 'month': {
        const startOn = dayjs().startOf('month')
        const finishOn = dayjs().endOf('month')
        // 请求接口
        const params = {
          project_id: projectId,
          start_on: new Date(startOn),
          finish_on: new Date(finishOn)
        }
        api.board.getReport(params).then(({ data }) => {
          const result = [`${finishOn.format('YYYY年MM月')}月报`]
          data.forEach((item, index) => {
            result.push(`${index + 1}.【${item.type_name}】${item.content}`)
          })
          setInitialValues({
            ...initialValues,
            content: result.join('\n')
          })
        })
        break
      }
      default: {
        break
      }
    }
  }
  // 抽象参数
  const getInitInitialValuesParams = type => {
    switch (type) {
      case 'daily': {
        const year = dayjs(reportTime).year() + ''
        const month = dayjs(reportTime).month() + 1 + ''
        const date = dayjs(reportTime).date() + ''
        const params = {
          project_id: projectId,
          year,
          month,
          date,
          type: 'daily'
        }
        return params
      }
      case 'month': {
        const year = dayjs(reportTime).year() + ''
        const month = dayjs(reportTime).month() + 1 + ''
        const params = {
          project_id: projectId,
          year,
          month,
          type: 'month'
        }
        return params
      }
      default: {
        return {}
      }
    }
  }
  const initInitialValues = () => {
    const params = getInitInitialValuesParams(type)
    api.report.list(params).then(({ data }) => {
      if (data.length) {
        const reportInfo = data[0]
        setInitialValues({
          ...initialValues,
          ...reportInfo
        })
      } else {
        getNewReport()
      }
    })
  }

  // 复制周报内容
  const handleCopy = () => {
    copyText(form.content).then(() => {
      message.success('复制成功')
    })
  }
  const handleSubmit = () => {
    let bForm = JSON.parse(JSON.stringify(form))
    // 保存日报/月报
    switch(type) {
      case 'daily': {
        bForm = {
          ...bForm,
          project_name: formOptions.projectList.find(item => item.id === bForm.project_id).value,
          type: 'daily',
          type_name: '日报',
          year: dayjs(bForm.reportTime).year() + '',
          month: dayjs(bForm.reportTime).month() + 1 + '',
          date: dayjs(bForm.reportTime).date() + '',
        }
        delete bForm.reportTime
        api.report.addOrUpdate(bForm).then(() => {
          message.success("打卡成功")
          const lastTab = tabList[tabList.length - 2]
          navigate(lastTab.path)
          dispatch(closeCurrentTab())
        })
        break
      }
      case 'month':
        bForm = {
          ...bForm,
          project_name: formOptions.projectList.find(item => item.id === bForm.project_id).value,
          type: 'month',
          type_name: '月报',
          year: dayjs(bForm.reportTime).year() + '',
          month: dayjs(bForm.reportTime).month() + 1 + '',
        }
        delete bForm.reportTime
        api.report.addOrUpdate(bForm).then(() => {
          message.success("打卡成功")
          const lastTab = tabList[tabList.length - 2]
          navigate(lastTab.path)
          dispatch(closeCurrentTab())
        })
        break
      default:
        break
    }
  }
  
  useEffect(() => {
    initProjectList()
    initInitialValues()
  }, [])

  const handleSave = () => {}
  return (
    <div>
      <HCTitle
        title={title}
        btnGroup={btnGroup}
        handleSave={handleSave}
        handleCopy={handleCopy}
        handleSubmit={handleSubmit}
      ></HCTitle>
      <ReportContent
        type={type}
        setForm={setForm}
        formOptions={formOptions}
        initialValues={initialValues}
        getNewReport={getNewReport}
      />
    </div>
  )
}

export default Report
